/**
 * 
 */
package org.pump.client.type;

import org.apache.mina.core.buffer.IoBuffer;
import org.pump.client.codec.AuthPack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liudong03
 *
 */
public class LengthCodedBinary {
	private static final Logger mylog = LoggerFactory.getLogger(LengthCodedBinary.class);
	byte binarytype;
	long binarydata;
	int len;
	/**
	 * 
	 */
	public LengthCodedBinary()
	{
		
	}
	public LengthCodedBinary(long data) {
		// TODO Auto-generated constructor stub
		long max_data = 0xffffffff;
		if(data <= 250 || data == 255)
		{
			this.binarytype = (byte)data;
			this.binarydata = data;
			this.len = 1;
		}
		else if(data == -1)
		{
			this.binarytype = (byte)251;
			this.binarydata = -1;
			this.len = 1;
		}else if(data > 255 && data <= 65535)
		{
			this.binarytype = (byte)252;
			this.binarydata = data;
			this.len = 3;
		}else if(data > 65535 && data <= max_data )
		{
			this.binarytype = (byte)253;
			this.binarydata = data;
			this.len = 5;
		}else if(data > max_data)
		{
			this.binarytype = (byte)254;
			this.binarydata = data;	
			this.len = 9;
		}
	}
	public static LengthCodedBinary readBuffer(IoBuffer in)
	{ 
		if(in.remaining() < 1)
		{
			return null;
		}
		LengthCodedBinary binary = new LengthCodedBinary();
		binary.binarytype = in.get();
		int temp = binary.binarytype & 0xff;
		if(temp <= 250 || temp == 255)
		{
			binary.binarydata = temp;
			binary.len = 1;
		}
		else if(temp == 251)
		{
			binary.binarydata = -1;
			binary.len = 1;
		}
		else if(temp == 252)
		{
			if(in.remaining() < 2)
			{
				return null;
			}
			binary.binarydata = in.getUnsignedShort();
			binary.len = 3;
		}
		else if(temp == 253)
		{
			if(in.remaining() < 4)
			{
				return null;
			}
			binary.binarydata = in.getUnsignedInt();
			binary.len = 5;
		}
		else if(temp == 254)
		{
			if(in.remaining() < 8)
			{
				return null;
			}
			binary.binarydata = in.getLong();
			binary.len = 9;
		}
		return binary;
	}
	
	public boolean writeBuffer(IoBuffer out)
	{
		int temp = this.binarytype & 0xff;
		out.put(binarytype);
		if(temp <= 251 || temp == 255)
		{
		}else if(temp == 252)
		{
			out.putUnsignedShort(binarydata);
		}else if(temp == 253)
		{
			out.putUnsignedInt(this.binarydata);
		}else if(temp == 254)
		{
			out.putLong(binarydata);
		}
		return true;
	}
	public long getData()
	{
		return this.binarydata;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "LengthCodedBinary [binarytype=" + binarytype + ", binarydata="
				+ binarydata + "]";
	}
	/**
	 * @return the len
	 */
	public int getLen() {
		return len;
	}
	

}
